# 创建商品编辑页面组件
<template>
  <div class="app-container">
    <el-page-header @back="goBack" :title="'返回商品列表'" :content="isEdit ? '编辑商品' : '新增商品'" />

    <el-card class="edit-card">
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="120px"
        class="product-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-cascader
              v-model="productForm.categoryId"
              :options="categoryOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }"
              placeholder="请选择商品分类"
            />
          </el-form-item>
          <el-form-item label="商品品牌" prop="brandId">
            <el-select v-model="productForm.brandId" placeholder="请选择品牌">
              <el-option
                v-for="item in brandOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="productForm.unit" placeholder="请输入商品单位" />
          </el-form-item>
        </div>

        <!-- 销售信息 -->
        <div class="form-section">
          <div class="section-title">销售信息</div>
          <el-form-item label="销售价格" prop="price">
            <el-input-number
              v-model="productForm.price"
              :precision="2"
              :step="0.1"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="市场价格" prop="marketPrice">
            <el-input-number
              v-model="productForm.marketPrice"
              :precision="2"
              :step="0.1"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="商品库存" prop="stock">
            <el-input-number
              v-model="productForm.stock"
              :min="0"
              :precision="0"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="库存预警值" prop="stockWarning">
            <el-input-number
              v-model="productForm.stockWarning"
              :min="0"
              :precision="0"
              controls-position="right"
            />
          </el-form-item>
        </div>

        <!-- 商品图片 -->
        <div class="form-section">
          <div class="section-title">商品图片</div>
          <el-form-item label="主图" prop="mainImage">
            <el-upload
              class="image-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleMainImageSuccess"
              :before-upload="beforeImageUpload"
            >
              <img v-if="productForm.mainImage" :src="productForm.mainImage" class="preview-image">
              <el-icon v-else class="upload-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="图片列表">
            <el-upload
              class="image-list-uploader"
              action="/api/upload"
              list-type="picture-card"
              :file-list="imageList"
              :on-success="handleImageSuccess"
              :on-remove="handleImageRemove"
              :before-upload="beforeImageUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 商品详情 -->
        <div class="form-section">
          <div class="section-title">商品详情</div>
          <el-form-item label="商品卖点" prop="sellingPoints">
            <el-input
              v-model="productForm.sellingPoints"
              type="textarea"
              :rows="3"
              placeholder="请输入商品卖点"
            />
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input
              v-model="productForm.description"
              type="textarea"
              :rows="6"
              placeholder="请输入商品描述"
            />
          </el-form-item>
        </div>

        <!-- 其他设置 -->
        <div class="form-section">
          <div class="section-title">其他设置</div>
          <el-form-item label="是否上架" prop="status">
            <el-radio-group v-model="productForm.status">
              <el-radio :label="'on_sale'">立即上架</el-radio>
              <el-radio :label="'off_sale'">暂不上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品排序" prop="sort">
            <el-input-number
              v-model="productForm.sort"
              :min="0"
              :precision="0"
              controls-position="right"
            />
          </el-form-item>
        </div>

        <div class="form-footer">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getProductDetail,
  createProduct,
  updateProduct
} from '@/api/product'
import { getCategoryList } from '@/api/product'

const route = useRoute()
const router = useRouter()
const productFormRef = ref(null)

// 是否编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const productForm = reactive({
  name: '',
  categoryId: '',
  brandId: '',
  unit: '件',
  price: 0,
  marketPrice: 0,
  stock: 0,
  stockWarning: 10,
  mainImage: '',
  sellingPoints: '',
  description: '',
  status: 'off_sale',
  sort: 0
})

// 图片列表
const imageList = ref([])

// 选项数据
const categoryOptions = ref([])
const brandOptions = ref([
  { id: 1, name: '品牌1' },
  { id: 2, name: '品牌2' }
])

// 表单校验规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择商品品牌', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入商品单位', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入销售价格', trigger: 'blur' }
  ],
  marketPrice: [
    { required: true, message: '请输入市场价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

// 获取商品详情
const getDetail = async (id) => {
  try {
    const { data } = await getProductDetail(id)
    Object.assign(productForm, data)
    imageList.value = data.images.map(url => ({ url }))
  } catch (error) {
    console.error('获取商品详情失败:', error)
  }
}

// 获取分类列表
const getCategoryOptions = async () => {
  try {
    const { data } = await getCategoryList()
    categoryOptions.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 返回列表
const goBack = () => {
  router.push('/product/list')
}

// 提交表单
const handleSubmit = async () => {
  if (!productFormRef.value) return
  try {
    await productFormRef.value.validate()
    const submitData = {
      ...productForm,
      images: imageList.value.map(item => item.url)
    }
    if (isEdit.value) {
      await updateProduct(route.params.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createProduct(submitData)
      ElMessage.success('添加成功')
    }
    router.push('/product/list')
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 图片上传相关
const handleMainImageSuccess = (response) => {
  productForm.mainImage = response.url
}

const handleImageSuccess = (response) => {
  imageList.value.push({ url: response.url })
}

const handleImageRemove = (file) => {
  const index = imageList.value.findIndex(item => item.url === file.url)
  if (index !== -1) {
    imageList.value.splice(index, 1)
  }
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

onMounted(() => {
  getCategoryOptions()
  if (isEdit.value) {
    getDetail(route.params.id)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.edit-card {
  margin-top: 20px;
}

.product-form {
  max-width: 980px;
  margin: 0 auto;
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid var(--el-color-primary);
}

.image-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.image-uploader:hover {
  border-color: var(--el-color-primary);
}

.preview-image {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.form-footer {
  margin-top: 30px;
  text-align: center;
}
</style> 